package com.lt.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lt.reggie.dto.SetmealDto;
import com.lt.reggie.entity.Setmeal;
import com.lt.reggie.entity.SetmealDish;
import com.lt.reggie.mapper.SetmealMapper;
import com.lt.reggie.service.SetmealDishService;
import com.lt.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 保存套餐信息和套餐菜品信息
     * @param setmealDto
     */
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐基本信息
        this.save(setmealDto);
        //保存套餐中菜品的信息
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();//菜品集合
        //将套餐id加入到套餐菜品信息中
        setmealDishes = setmealDishes.stream().map((item) ->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 删除或批量删除套餐
     * @param ids
     */
    @Override
    @Transactional
    public void deleteByIdsWithDish(List<Long> ids) {
        //删除套餐信息
        this.removeByIds(ids);

        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetmealDish::getSetmealId,ids);
        //删除套餐菜品信息
        setmealDishService.remove(queryWrapper);
    }
}
